const express = require("express");
const router = express.Router();
const multer = require("multer");
const path = require("path");
const fs = require("fs");
const { Worker } = require("worker_threads");
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    console.log("file", file);
    // 文件存储地址
    let desPath = "";
    if (req.url.startsWith("/slice")) {
      desPath = path.resolve(
        __dirname,
        "../../resources",
        file.originalname.split("-")[0]
      );
      // console.log("slice", file);
    } else {
      const ext = path.extname(file.originalname);
      desPath = path.resolve(__dirname, "../../resources", ext.split(".")[1]);
    }
    // 检查目录是否存在，如果不存在则创建
    if (!fs.existsSync(desPath)) {
      console.log("目录不存在，创建目录", desPath);
      fs.mkdirSync(desPath, { recursive: true });
    }
    console.log("desPath", desPath);
    cb(null, desPath);
  },
  filename: function (req, file, cb) {
    const timeStamp = Date.now();
    const ext = path.extname(file.originalname);
    const randomNum = Math.random().toString(36).slice(-6);
    // 存储文件名
    let fileName = `${timeStamp}-${randomNum}${ext}`;
    if (req.url.startsWith("/slice")) {
      fileName = `${file.originalname}`;
    }
    cb(null, fileName);
  },
});

const upload = multer({
  storage: storage,
  fileFilter(req, file, cb) {
    try {
      console.log("fileFilter", req.url);
      if (req.url.startsWith("/slice")) {
        const filePath = path.resolve(
          __dirname,
          "../../resources",
          file.originalname.split("-")[0],
          file.originalname
        );
        // console.log("filePath", filePath);
        if (fs.existsSync(filePath)) {
          console.log(`${file.originalname}文件已存在`);
          req.file = file;
          cb(null, false);
          return;
        }
      }
      cb(null, true);
    } catch (error) {
      cb(new Error(error.message));
    }
  },
});
// 单个文件上传 upload.single("file")充当中间件，调用返回一个函数，该函数会处理客户端上传过来的文件，并将处理好的文件信息挂载到req.file上
router.post("/", upload.single("file"), (req, res, next) => {
  console.log(req.file);
  const {
    file: { filename },
  } = req;
  const ext = path.extname(filename);
  res.json({
    code: 200,
    message: "上传成功",
    data: {
      url: `/resources/${ext.split(".")[1]}/${filename}`,
    },
  });
});

// 多个文件上传
router.post("/multiple", upload.array("file", 10), (req, res, next) => {
  const { files } = req;
  console.log("files", files);
  const urls = files.map((file) => {
    const { filename } = file;
    const ext = path.extname(filename);
    return `/resources/${ext.split(".")[1]}/${filename}`;
  });
  res.json({
    code: 200,
    message: "上传成功",
    data: {
      urls,
    },
  });
});

// 大文件分片上传
router.post("/slice", upload.single("slice"), (req, res, next) => {
  // console.log("slice", req.file);
  res.json({
    code: 200,
    message: `${req.file.originalname}上传成功`,
  });
});

// 合并文件
router.post("/merge", (req, res, next) => {
  console.log("merge", req.body);
  // 开启子线程，处理文件合并
  const worker = new Worker(
    path.resolve(__dirname, "../../utils/mergeWorker.js"),
    {
      workerData: {
        data: req.body,
      },
    }
  );
  worker.on("message", (message) => {
    console.log("message", message);
    if (message.code === 500) {
      res.status(500).send("文件合并失败！");
    } else {
      res.json(message);
    }
  });
});
module.exports = router;
